#include "DeviceManager.hpp"
#include <stdlib.h>
#if defined(__WIN32) || defined(__WINNT)
#include <windows.h> //http://msdn.microsoft.com/en-us/library/windows/desktop/aa364939(v=vs.85).aspx
#endif
/*#ifdef _UNICODE
typedef wchar_t TCHAR;
#define _tcslen wcslen
#else
typedef char TCHAR;
#define _tcslen strlen
#endif*/
typedef wchar_t TCHAR;
#define _tcslen wcslen
#ifdef __LINUX
#include <blkid/blkid.h>
#endif

bool DeviceManager::isRemovable(QString path) {
#if defined(__WIN32) || defined(__WINNT)
    QFileInfoList fil=QDir::drives();
    for(int i=0; i<fil.size(); i++)
        if(path.contains(fil.at(i).absoluteFilePath())) {
            UINT uDriveType = GetDriveType(fil.at(i).absoluteFilePath().replace("/","\\").toStdWString().c_str());
            if(uDriveType!=DRIVE_FIXED && uDriveType!=DRIVE_RAMDISK) return true;
        }
#endif
#ifdef __LINUX
    //http://unix.stackexchange.com/questions/40143/how-to-know-if-dev-sdx-is-a-connected-usb-or-hdd
    //http://linux.die.net/man/8/mount =-> context=system_u:object_r:removable_t
#endif
    return false;
}

QString DeviceManager::getUuid(QString path) {
    QFileInfoList fil=QDir::drives();
    QString tmp="";
#if defined(__WIN32) || defined(__WINNT)
    for(int i=0; i<fil.size(); i++)
        if(path.contains(fil.at(i).absoluteFilePath())) {
            wchar_t buf[50];
            GetVolumeNameForVolumeMountPoint(fil.at(i).absoluteFilePath().replace("/","\\").toStdWString().c_str(), buf, 50);
            tmp=QString::fromWCharArray(buf);
        }
#endif
#ifdef __LINUX
    QFile f("/proc/mounts");
    QRegExp rx("([\\S]+)[\s]+([\\S]+)[\s]+([\\S]+)[\s]+([\\S]+)[\s]+([\\S]+)[\s]+([\\S]+)");
    f.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream ts(&f);
    while(!ts.atEnd()) {
        QString line=ts.readLine().trimmed();
        if(line.at(0)=="#") continue; //ignore comments
        if(rx.exactMatch(line)) {
            if(path.startsWith(rx.cap(2))) return blkid_evaluate_spec(rx.cap(2).toLocal8Bit().constData(), NULL);
        }
    }
    f.close();
#endif
    return tmp;
}
